package icst.cyber.hrm.actions;

import icst.cyber.hrm.bo.PersonBO;
import icst.cyber.hrm.forms.LogonActionForm;
import icst.cyber.hrm.forms.LogonSessionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * @author NGOCLAN
 * 
 */
public class LogonAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		ActionMessages errors = new ActionMessages();
		ActionForward forward = new ActionForward();

		LogonActionForm logonForm = (LogonActionForm) form;
		String username = logonForm.getUsername();
		String password = logonForm.getPassword();

		PersonBO accBO = new PersonBO();
		if (accBO.isValidAccount(username, password)) {
			int id_emp = accBO.getIdEmpByAccount(username, password);

			if (!accBO.isActiveEmployee(id_emp)) {
				errors.add("common.notactive.err", new ActionMessage(
						"error.logon.notactive"));
			}
		} else {
			errors.add("common.isvalid.err", new ActionMessage(
					"error.logon.isvalid"));
		}

		if (!errors.isEmpty()) {
			saveErrors(request, errors);
			forward = mapping.findForward("fail");
		} else {
			int id_emp = accBO.getIdEmpByAccount(username, password);
			LogonSessionForm sessionForm = accBO.getSessionLogon(id_emp);

			session.setAttribute("_ACCOUNTINFO", sessionForm);
			forward = mapping.findForward("success");
		}
		return forward;
	}
}
